package com.rbac.web.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbac.web.db.UserDAO;
import com.rbac.web.db.UserDO;
import com.rbac.web.service.IUserService;
import com.rbac.web.model.PageResult;
import com.rbac.web.model.PageV0;
import com.rbac.web.model.User;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author gengaoliu
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements IUserService {
  private final UserDAO dao;

  @Override
  public void save(User user) {
    dao.insert(UserDO.from(user));
  }

  @Override
  public PageResult<User> query(PageV0 pageV0, String name) {
    IPage<UserDO> page =
        dao.selectPage(
            Page.of(pageV0.getPage(), pageV0.getSize()),
            Wrappers.<UserDO>lambdaQuery().like(StringUtils.hasText(name), UserDO::getName, name));
    List<User> res = page.getRecords().stream().map(UserDO::to).toList();
    return PageResult.of(page.getCurrent(), page.getPages(), page.getTotal(), res);
  }

  @Override
  public User findById(Integer id) {
    return Optional.of(dao.selectById(id)).map(UserDO::to).orElse(null);
  }

  @Override
  public void deleteById(Integer id) {
    dao.deleteById(id);
  }

  @Override
  public void updateById(User user) {
    dao.updateById(UserDO.from(user));
  }

  @Override
  public List<User> selectList() {
    return dao.selectList(null).stream().map(UserDO::to).toList();
  }

  @Override
  public Optional<User> findByUsername(String username) {
    UserDO one = dao.selectOne(Wrappers.<UserDO>lambdaQuery().eq(UserDO::getUsername, username));
    return Optional.of(one).map(UserDO::to);
  }
}
